package managers.conversationManager;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import managers.conversationManager.services.ContactUserService;

import spotGUI.floatingChatGUI.FloatingChat;
import spotGUI.floatingChatGUI.FloatingChatFrame;
import utils.UserData;

public class DefaultUserRequestsManager implements UserRequestsManager {

	private ConversationManager convManager = ConversationManager.getSharedInstance();
	
	private Map<Integer, ContactUserService> pendingConnections = Collections.synchronizedMap(new HashMap<Integer, ContactUserService>());

	
	public void removePendingConnection (int id) {
		pendingConnections.remove(id);
	}
	
	
	public void requestUserDataAndContactUser (UserData user) {
		FloatingChat chat = ConversationManager.getSharedInstance().getChatManager().getChat((Integer) user.getProperty("id"));
		if (chat == null) {
			chat = new FloatingChatFrame();
			chat.setReceiverName(user.getProperty("firstName")+" "+user.getProperty("surname"));
			convManager.getChatManager().addChat((Integer) user.getProperty("id"), chat);
			doRequest(user, chat);
		} else {
			if (chat.getConversation() instanceof OnlineConversation) {
				chat.setVisible(true);
			} else {
				doRequest(user, chat);
			}
		}
	}

	
	private void doRequest(UserData user, FloatingChat chat) {
		chat.updateStatus(ResourceBundle.getBundle("managers.conversationManager.messages").getString("m.1"), FloatingChat.WORKING_ICON);
		chat.setEnabled(false);
		chat.setVisible(true);

		ContactUserService thread = new ContactUserService((Integer) user.getProperty("id"), chat);
		pendingConnections.put((Integer) user.getProperty("id"), thread);
		thread.start();
	}

	public void ackUserDataRequest (UserData data) {
		ContactUserService service = pendingConnections.get(data.getProperty("id"));
		service.wakeUp(data);
	}
	
}
